<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebSocket 聊天室</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        #chat-container {
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            overflow: hidden;
        }
        #messages {
            height: 400px;
            overflow-y: auto;
            padding: 15px;
            border-bottom: 1px solid #eee;
        }
        .message {
            margin-bottom: 10px;
            padding: 8px 12px;
            border-radius: 4px;
            background-color: #f0f0f0;
        }
        .my-message {
            background-color: #e3f2fd;
            text-align: right;
        }
        .system-message {
            background-color: #fff8e1;
            font-style: italic;
        }
        #message-form {
            display: flex;
            padding: 15px;
        }
        #message-input {
            flex-grow: 1;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            margin-right: 10px;
        }
        #send-button {
            padding: 10px 20px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        #send-button:hover {
            background-color: #45a049;
        }
        #status {
            padding: 10px 15px;
            background-color: #f8f9fa;
            color: #6c757d;
            font-size: 14px;
        }
        .user-count {
            float: right;
        }
    </style>
</head>
<body>
    <h1>WebSocket 聊天室</h1>
    <div id="chat-container">
        <div id="status">
            连接状态: <span id="connection-status">未连接</span>
            <span class="user-count">在线用户: <span id="user-count">0</span></span>
        </div>
        <div id="messages"></div>
        <form id="message-form">
            <input type="text" id="message-input" placeholder="输入消息..." autocomplete="off">
            <button type="submit" id="send-button">发送</button>
        </form>
    </div>

    <script>
        // WebSocket 连接
        let socket;
        let userId = Math.random().toString(36).substring(2, 10); // 生成随机用户ID

        // 连接 WebSocket 服务器
        function connect() {
            // 替换为您的服务器地址
            const wsUrl = "ws://localhost:9090/websocket";
            
            socket = new WebSocket(wsUrl);
            
            socket.onopen = function(e) {
                updateStatus("已连接", "green");
                addSystemMessage("已连接到聊天服务器");
            };
            
            socket.onmessage = function(event) {
                const message = event.data;
                displayMessage(message);
            };
            
            socket.onclose = function(event) {
                if (event.wasClean) {
                    updateStatus("已断开", "gray");
                    addSystemMessage(`连接关闭，代码=${event.code} 原因=${event.reason}`);
                } else {
                    updateStatus("连接中断", "red");
                    addSystemMessage("连接中断");
                    // 尝试重新连接
                    setTimeout(connect, 5000);
                }
            };
            
            socket.onerror = function(error) {
                updateStatus("连接错误", "red");
                addSystemMessage(`发生错误: ${error.message}`);
            };
        }
        
        // 更新连接状态显示
        function updateStatus(text, color) {
            const statusElement = document.getElementById("connection-status");
            statusElement.textContent = text;
            statusElement.style.color = color;
        }
        
        // 添加系统消息
        function addSystemMessage(text) {
            const messagesElement = document.getElementById("messages");
            const messageElement = document.createElement("div");
            messageElement.className = "message system-message";
            messageElement.textContent = text;
            messagesElement.appendChild(messageElement);
            messagesElement.scrollTop = messagesElement.scrollHeight;
        }
        
        // 显示收到的消息
        function displayMessage(rawMessage) {
            // 解析消息格式：客户端【id】时间：消息内容
            const regex = /(客户端|我|系统)\【(.+?)\】(.+?)：(.*)/;
            const match = rawMessage.match(regex);
            
            const messagesElement = document.getElementById("messages");
            const messageElement = document.createElement("div");
            
            if (match) {
                const type = match[1];
                const senderId = match[2];
                const time = match[3];
                const content = match[4];
                
                messageElement.className = type === "我" ? "message my-message" : "message";
                messageElement.innerHTML = `<strong>${type === "系统" ? "系统通知" : (type === "我" ? "我" : "用户 "+senderId)}</strong> 
                                          <small>(${time})</small><br>${content}`;
            } else {
                // 如果不是标准格式，直接显示
                messageElement.className = "message";
                messageElement.textContent = rawMessage;
            }
            
            messagesElement.appendChild(messageElement);
            messagesElement.scrollTop = messagesElement.scrollHeight;
        }
        
        // 发送消息
        document.getElementById("message-form").addEventListener("submit", function(event) {
            event.preventDefault();
            const input = document.getElementById("message-input");
            const message = input.value.trim();
            
            if (message && socket && socket.readyState === WebSocket.OPEN) {
                socket.send(message);
                input.value = "";
            }
        });
        
        // 初始化连接
        connect();
        
        // 添加用户名提示
        addSystemMessage(`您的用户ID: ${userId}`);
    </script>
</body>
</html>